package com.szpxt.service;

import java.util.ArrayList;
import java.util.List;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.hibernate.criterion.DetachedCriteria;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import org.springframework.stereotype.Component;

import com.szpxt.model.Privilege;

@Component
public class PrivilegeService extends HibernateDaoSupport {

	public List<Privilege> getAll() {
		DetachedCriteria criteria = DetachedCriteria.forClass(Privilege.class);
		return (List<Privilege>)getHibernateTemplate().findByCriteria(criteria);
	}
	
	public void inititalize() throws DocumentException {
		String directory = PrivilegeService.class.getResource("/").getPath();
		
		SAXReader reader = new SAXReader();
		Document document = reader.read(directory + "privilege.xml");
		Element root = document.getRootElement();
		List<Element> listElement = (List<Element>)root.elements();
		
		List<Privilege> listPrivilege = new ArrayList<Privilege>();
		for(Element element: listElement) {
			String key = element.attributeValue("key");
			String name = element.attributeValue("name");
			
			Privilege privilege = new Privilege();
			privilege.setKey(key);
			privilege.setName(name);
			
			if(!isExist(privilege)) {
				listPrivilege.add(privilege);
			}
		}
		
		getHibernateTemplate().saveOrUpdateAll(listPrivilege);
	}
	
	public boolean isExist(Privilege privilege) {
		List list = getHibernateTemplate().findByExample(privilege);
		return (list.size() > 0) ? true : false;
	}
}
